package com.vf.admin.client.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.vf.admin.client.dao.WxAppidConifgDao;
import com.vf.admin.client.service.WxAppidConifgService;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.miaodong.entity.AlipayConfigs;
import com.vf.admin.miaodong.entity.WxAppidConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * <p>Title : </p>
 * <p>Description : </p>
 * <p>DevelopTools : IDEA</p>
 * <p>DevelopSystem : Windows11</p>
 *
 * @Author : NemoMeng
 * @Date 2023/12/27 11:56
 */
@Service
public class WxAppidConifgServiceImpl implements WxAppidConifgService {

    @Autowired
    private WxAppidConifgDao wxAppidConifgDao;


    @Override
    public WxAppidConfig getWxAppidConifg(String appId) {
        //根据appId获取
        WxAppidConfig appidConfig = wxAppidConifgDao.getByAppId(appId);
        //
        List<WxAppidConfig> wxAppidConfigs = new ArrayList<>();
        //
        String[] mchIds = appidConfig.getMchIds().split(",");
        String[] weights = appidConfig.getWeight().split(",");
        //比对配置文件是否一致
        if (mchIds.length == weights.length){
            //
            for (int i = 0; i < mchIds.length; i++) {
                String mchId = mchIds[i];
                String weight = weights[i];
                //数据组装
                WxAppidConfig result = new WxAppidConfig();
                result.setAppId(appId);
                result.setMchIds(mchId);
                result.setWeight(weight);
                wxAppidConfigs.add(result);
            }
        }
        Integer sumWeight = 0;//总权重的值
        JSONArray as = new JSONArray();//存入对象用于概率
        Integer index = 0;
        for (int i = 0; i < wxAppidConfigs.size(); i++) {
            Integer weight = Integer.valueOf(wxAppidConfigs.get(i).getWeight());
            if (weight > 0) {
                sumWeight = sumWeight + weight;
                for (int j = 0; j < weight; j++) {
                    as.add(index, wxAppidConfigs.get(i));
                    index++;//放后面保证0也有值
                }
            }
        }
        Integer r = new Random().nextInt(sumWeight + 1);//随机数生成概率
        WxAppidConfig wxAppidConfig = (WxAppidConfig)as.get(r);
        return wxAppidConfig;
    }
}
